Model.java
package example;
import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;
import java.util.function.Consumer;
/**
* Simple model that notifies view objects when its value has changed.
*
* @author Robert C. Duvall
*/
public class Model {
// constants
// use Java's dot notation, like with import, for properties files
public static final String DEFAULT_RESOURCES = "example.Model";
// model is basically just this value
private String myValue;
// view objects to update when value changes (Consumer is the object created when using Lambda syntax)
private List<Consumer<String>> mySetters;
// language specific strings to initialize model values that will be passed to view
private ResourceBundle myResources;
/**
* Create model in given language
*/
public Model (String language) {
myResources = ResourceBundle.getBundle(DEFAULT_RESOURCES + language);
myValue = myResources.getString("Value");
mySetters = new ArrayList<>();
}
/**
* Change model's value and notify any interested view objects
*/
public void setValue (String value) {
if (value != null && ! value.isBlank()) {
myValue = value;
updateSetters();
}
}
/**
* Add action to be called when model's value is updated
*/
public void addSetter (Consumer<String> observer) {
if (observer != null) {
mySetters.add(observer);
}
}
// call all interested view actions
private void updateSetters () {
for (Consumer<String> h : mySetters) {
h.accept(myValue);
}
}
}